package oop.conf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;

import com.thoughtworks.xstream.XStream;

public class ConfigIO {

	private final static XStream xstream;
	
	static {
		xstream = new XStream();
		xstream.alias("config", Config.class);
		xstream.alias("action", ActionDescriptor.class);
		xstream.alias("module", ModuleDescriptor.class);
		xstream.aliasField("actions", Config.class, "actionDescriptors");
		xstream.aliasField("modules", Config.class, "moduleDescriptors");
		xstream.aliasField("dbname", Config.class, "databaseName");
		xstream.aliasField("dbport", Config.class, "databasePort");
		xstream.aliasField("dbhost", Config.class, "databaseHost");
		xstream.aliasField("class", ActionDescriptor.class, "clazz");
		xstream.aliasField("class", ModuleDescriptor.class, "clazz");
	}
	
	public static void load(File file, Config config) throws IOException {
		FileInputStream input = null;
		try {
			input = new FileInputStream(file);
			xstream.fromXML(input, config);
		} finally {
			if (input != null) {
				input.close();
			}
		}
	}

	public static void loadDirectory(Config config, String dirPath) {
		File dir = new File(dirPath);
		File[] confFiles = dir.listFiles(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".xml");
			}
		});
		for (File file : confFiles) {
			try {
				load(file, config);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

}
